package com.qlylkj.lbk.share

import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.qlylkj.lbk.R
import com.ysyc.ytszapp.share.ShareScene
import kotlinx.android.synthetic.main.dialog_fragment_share_scene.*


class ShareSceneDialogFragment : BottomSheetDialogFragment() {

    companion object {
        fun newInstance(
            shareSceneList: MutableList<ShareScene>,
            onShareSceneListener: OnShareSceneListener,
            title: String = "请选择邀请方式"
        ): ShareSceneDialogFragment {
            val instance = ShareSceneDialogFragment()
            instance.mOnShareSceneListener = onShareSceneListener
            instance.mShareSceneList = shareSceneList
            instance.title = title
            return instance
        }
    }

    private var title = ""

    private var mShareSceneList: MutableList<ShareScene> = mutableListOf()

    private var mOnShareSceneListener: OnShareSceneListener? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_fragment_share_scene, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initView()
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        // 解决dialog黑屏问题
        val dialog = super.onCreateDialog(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            dialog.window?.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        }
        return dialog
    }

    private fun initView() {
        shareTitleText.text = title
        shareRecyclerView.apply {
            context?.run {
                val spanCount = if (mShareSceneList.size >= 4) 4 else mShareSceneList.size
                layoutManager = GridLayoutManager(this, spanCount)
                adapter = ShareSceneAdapter(mShareSceneList).apply {
                    setOnItemClickListener { _, _, position ->
                        mOnShareSceneListener?.shareScene(mShareSceneList[position].scene)
                        dismiss()
                    }
                }
            }
        }
        cancelShareText.setOnClickListener {
            dismiss()
            mOnShareSceneListener?.dismiss()
        }
    }

    interface OnShareSceneListener {

        fun shareScene(scene: String)

        fun dismiss()
    }


}